<template>
  <div class="websocket-demo-wrapper">
    <div class="component-example">
      <label class="example-title">使用示例</label>
      <div class="example">
        <!--        <img src="static/images/websocket.png" width="689" height="551"/>-->
        广播式<el-button type="primary" size="small" plain @click="start">开始接收数据</el-button>
        <div class="socket-container" ref="broadcastRef">
          <p v-for="(point, index) in broadcastData" :key="index">{{ point }}</p>
        </div>
        点对点
        <el-button type="primary" size="small" plain @click="pointToPointSocket">向服务器发出指示后推送消息</el-button>
        <div class="socket-container" ref="pointToPointRef">
          <p v-for="(point, index) in pointToPointData" :key="index">{{ point }}</p>
        </div>
      </div>
    </div>
    <div class="component-document">
      <div class="import-property">
        <label class="prop-title">输入属性</label>
        <ul class="prop-lists">
          <li class="prop-item" v-for="(item,index) in webSocketProps" :key="index">
            <label class="prop-name">{{ item.name }}：</label>
            <div class="prop-desc">
              <span> {{ item.desc }}</span>
              <div class="sub-element-lists" v-if="item.lists && item.lists.length !== 0">
                <ul class="sub-lists">
                  <li class="sub-item" v-for="(op,i) in item.lists" :key="i">
                    <label class="sub-prop-name">{{ op.name }}：</label>
                    <span class="sub-prop-value">{{ op.desc }}</span>
                  </li>
                </ul>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import {SWebSocket} from "../../utils/WebSocket/WebSocket";

export default {
  name: "WebsocketDemo",
  data() {
    return {
      websocketUrl: websocketUrl + '/demo/webSocketServer', // 连接地址
      headers: {
        Authorization: new Date().getTime() + Math.floor(Math.random() * 100)
      },
      broadcastAddress: '/topic/message', // 广播地址
      broadcastInfo: '/app/topic', // 广播的前端给后台发消息地址
      pointToPointAddress: '/user/queue/message', // 点对点地址
      pointToPointInfo: '/app/queue', // 点对点的 前端给后台发消息地址
      broadcastData: [], // 广播数据
      pointToPointData: [], // 点对点数据
      webSocketProps: [
        {name: '使用方式', desc: '直接以第三方js引入或者import到组件中'},
        {name: '说明', desc: '根据传递的参数个数，自动判断参数的个数。3个参数为ES6中websocket的连接方式，4个参数以上为SockJS的连接方式（与后台通用，常使用此方法）'},
        {name: 'SockJS方式（常用）参数介绍', desc: ''},
        {name: "参数1", desc: 'websocket的连接地址'},
        {name: "参数2", desc: '订阅地址'},
        {name: "参数3", desc: '回调函数'},
        {name: "参数4", desc: '参数项,如{name:"token"}'},
        {
          name: "参数5",
          desc: '向后台发送数据（可选），数据类型为Array',
          lists: [
            {name: "参数1", desc: '匹配的URL，数据类型为String，（如果需要向服务器发送数据，此项必填）'},
            {name: "参数2", desc: '发送信息的header，数据类型为Object，（可选参数）'},
            {name: "参数3", desc: '为发送信息的 body，String，（可选参数）'},
          ]
        },
        {name: 'websocket方式参数介绍', desc: ''},
        {name: "参数1", desc: 'websocket的连接地址'},
        {name: "参数2", desc: '回调函数'},
        {name: "参数3", desc: '连接参数项，如{name:"token"}'},
      ]
    }
  },
  mounted() {

  },
  methods: {
    start(){
      this.broadcastSocket()
    },
    // 广播
    broadcastSocket() {
      new SWebSocket(this.websocketUrl, this.broadcastAddress, res => {
        this.broadcastData.push(res.body);
        if (this.broadcastData.length > 100) {
          this.broadcastData.shift()
        }
        if (this.$refs['broadcastRef']) {
          this.$nextTick(() => {
            this.$refs['broadcastRef'].scrollTop = this.$refs['broadcastRef'].scrollHeight
          })
        }
      }, this.headers, [this.broadcastInfo, {}, 'hello！！！']).then(res => {
        // 这里是ws实例，方便定制化操作
      })
    },
    // 点对点（只有向服务器发出指示才推送消息）
    pointToPointSocket() {
      new SWebSocket(this.websocketUrl, this.pointToPointAddress, res => {
        this.pointToPointData.push(res.body);
        if (this.pointToPointData.length > 100) {
          this.pointToPointData.shift()
        }
        if (this.$refs['pointToPointRef']) {
          this.$nextTick(() => {
            this.$refs['pointToPointRef'].scrollTop = this.$refs['pointToPointRef'].scrollHeight
          })
        }
      }, this.headers, [this.pointToPointInfo, {}, 'hello！！！'])
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../assets/styles/base_style";

.websocket-demo-wrapper {
  width: 100%;
  height: 100%;

  .socket-container {
    width: 100%;
    height: calc(50% - 100px);
    border: 1px solid #b3b1fa;
    overflow-y: auto;
    margin: 10px 0;
    padding: 0 10px;
    border-radius: 5px;
    @include scrollbarStyle(6px, 3px, null, #58a1f3);
  }
}
</style>
